<template>
  <div>

    <el-row>
      <el-col :span="1">
        <el-button type="primary" @click="dialogVisible = true" icon="el-icon-plus">新增</el-button>
      </el-col>
    </el-row>

    <!-- 列表数据 -->
    <el-table :data="pageResult.list" stripe border>
      <el-table-column prop="name" label="名称"></el-table-column>
      <el-table-column prop="code" label="编码"></el-table-column>
      <el-table-column prop="num" label="序号"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" size="mini" @click="get(scope.row.id)">编辑</el-button>
          <el-button v-if="scope.row.id!==1" type="text" icon="el-icon-setting" size="mini" @click="showMenuDialog(scope.row.id)">菜单</el-button>
          <el-button v-if="scope.row.id!==1" type="text" icon="el-icon-delete" size="mini" @click="remove(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                   :current-page="pageResult.pageNum" :page-size="pageResult.pageSize" :total="pageResult.total"
                   :page-sizes="[5, 10]" layout="total, sizes, prev, pager, next"
    >
    </el-pagination>

    <!-- 角色编辑模态 -->
    <el-dialog title="角色" :visible.sync="dialogVisible" width="30%" @close="closeDialog">
      <!-- 主体 -->
      <el-form ref="itemRef" :model="item" :rules="itemRules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="item.name" clearable></el-input>
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="item.code" clearable :disabled="this.item.id===1"></el-input>
        </el-form-item>
        <el-form-item label="序号" prop="num">
          <el-input-number v-model="item.num" :min="2" :max="100" :step="1" step-strictly :disabled="this.item.id===1"></el-input-number>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="postData">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 角色-菜单模态 -->
    <el-dialog title="菜单" :visible.sync="menuDialogVisible" width="30%" @close="closeMenuDialog">
      <el-tree :data="menuAllList"
               show-checkbox
               node-key="id"
               ref="tree"
               default-expand-all
               highlight-current
               @check="check"
               :props="defaultProps">
      </el-tree>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="menuDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="postTree">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data () {
    return {
      // 查询条件
      searcher: {
        pageNum: 1,
        pageSize: 10
      },
      // 分页结果
      pageResult: {
        // 分页列表数据
        list: [],
        // 数据总条数
        total: 0,
        // 数据总页数
        pages: 0,
        // 当前页
        pageNum: 1,
        // 当前分页条数
        pageSize: 10
      },
      // 模态显示
      dialogVisible: false,
      menuDialogVisible: false,
      // 单个数据
      item: {
        id: 0,
        name: '',
        code: '',
        num: 0
      },
      // 所有角色-菜单
      menuAllList: [],
      // 角色-菜单关系模态，当前选择 roleId
      menuCurrentRole: 0,
      // 模态校验
      itemRules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 10, message: '名称在 1 到 10 个字符之间', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入编码', trigger: 'blur' },
          { min: 1, max: 10, message: '编码在 1 到 10 个字符之间', trigger: 'blur' }
        ],
        num: [
          { required: true, message: '请输入序号', trigger: 'blur' }
        ]
      },
      // tree 参数
      defaultProps: {
        label: 'name'
      }
    }
  },
  created () {
    // 所有角色
    this.list()
    // 获取所有角色-菜单
    this.listAllMenu()
  },
  methods: {
    // 所有角色
    async list () {
      const { data } = await this.$axios.post('/role/list', this.searcher)
      this.pageResult = data
    },
    async listAllMenu () {
      const { data } = await this.$axios.post('/menu/listSingleAll')
      this.menuAllList = data.data
    },
    // 查询, 每次查询，从第 1 页开始展示数据
    query () {
      this.searcher.pageNum = 1
      this.list()
    },
    // 分页每页展示数据量变更
    handleSizeChange (crrentPageSize) {
      this.searcher.pageSize = crrentPageSize
      this.list()
    },
    // 分页当前页码变更
    handleCurrentChange (currentPage) {
      this.searcher.pageNum = currentPage
      this.list()
    },
    // 模态关闭
    closeDialog () {
      // 重置校验
      this.$refs.itemRef.resetFields()
    },
    // 详情
    async get (id) {
      const { data } = await this.$axios.post('/role/get', { id: id })
      this.item = data.data
      this.dialogVisible = true
    },
    // 提交修改
    async postData () {
      this.$refs.itemRef.validate(async valid => {
        if (valid) {
          let requestUrl
          if (this.item.id) {
            requestUrl = '/role/update'
          } else {
            requestUrl = '/role/save'
          }
          const { data } = await this.$axios.post(requestUrl, this.item)
          // 后续操作：弹窗、关模态、刷新分页、清空表单数据
          this.$message.success(data.msg)
          this.dialogVisible = false
          this.list()
          this.closeDialog()
        }
      })
    },
    // 删除, confirm
    async remove (id) {
      const confirmResult = await this.$confirm('将删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult === 'confirm') {
        const { data } = await this.$axios.post('/role/delete', { id: id })
        this.$message.success(data.msg)
        this.list()
      }
    },
    // 角色-菜单模态显示
    async showMenuDialog (roleId) {
      this.menuDialogVisible = true
      // 模态当前选择角色 id
      this.menuCurrentRole = roleId
      // 当前角色菜单勾选
      const { data } = await this.$axios.post('/menu/listByRole', { roleId: roleId })
      let halfCheckedKeys = []
      halfCheckedKeys = data.data
      console.log(JSON.stringify(halfCheckedKeys))
      for (let item of halfCheckedKeys) {
        this.$refs.tree.setChecked(item.menuId, true, false)
      }
    },
    // 角色-菜单模态关闭
    closeMenuDialog () {
      this.menuDialogVisible = false
      this.$refs.tree.setCheckedKeys([])
      // 获取所有角色-菜单
      this.listAllMenu()
    },
    // 提交树节点数据
    async postTree () {
      console.log('getCheckedKeys: ' + this.$refs.tree.getCheckedKeys())
      const { data } = await this.$axios.post('/menu/updateRoleMenu', { roleId: this.menuCurrentRole, selectIds: this.$refs.tree.getCheckedKeys() })
      this.$message.success(data.msg)
      this.closeMenuDialog()
    },
    // tree 节点选择，触发时间
    check () {
      let halfCheckedKeys = []
      halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys()
      for (let item of halfCheckedKeys) {
        this.$refs.tree.setChecked(item, true, false)
      }
    }
  }
}
</script>

<style lang="less" scoped>

</style>
